// 和用户相关的数据
import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo, getUserDetailById } from '@/api/user'

const state = {
  token: getToken() || null, // 用户的token
  userInfo: {} // 用户信息
}

const mutations = {
  // 设置token
  setToken(state, newToken) {
    state.token = newToken
    setToken(state.token)
  },
  // 删除token
  removeToken(state) {
    state.token = null
    removeToken()
  },
  // 设置userInfo
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  // 移除userInfo
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  // 用户登录
  async userLogin(context, obj) {
    const res = await login(obj)
    // console.log(res)
    context.commit('setToken', res.data)
  },
  // 获取用户信息
  async getUserInfo(context) {
    const res = await getUserInfo()
    // console.log(res.data)
    const userInfo = await getUserDetailById(res.data.userId)
    // console.log(userInfo)
    context.commit('setUserInfo', { ...res.data, ...userInfo.data })
  },
  // 退出 (删除token/删除userInfo)
  userLogout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

